<?php

namespace App\Models\Ddaman;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use App\Models\common\Base;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class WorkflowFlowRule extends Base
{
    use HasFactory;

    protected $table = "workflow_flow_rule";

    //const CREATED_AT = null;
    //const UPDATED_AT = null;

    protected $fillable = [
        'flow_id','type_id','level','user_id','position_id','approve_type'
    ];

    public static $fill = [
        'flow_id','type_id','level','user_id','position_id','approve_type'
    ];


    public $rule = [
        'name' => 'required|string|between:2,100',
        'logo' => 'required',
    ];

    public $editRule = [
        'id' => 'required',
        'name' => 'required|string|between:2,100',
        'logo' => 'required',
    ];

    public $message = [
        'id.required' => '标识必须',
        'name.required' => '分类名称必须填写',
        'logo.required'=>"请上传品牌logo",
    ];

    /*
     * 获取列表
     * */
    public function getList( $param = [] )
    {
        $limit = isset($param['limit']) ? $param['limit'] : 10;
        $where = [];

        if (isset($param['keywords']) && $param['keywords']){
            $keywords = trim($param['keywords']);
            $where[] = ['name','like',"%$keywords%"];
        }

        $field = array_merge(['id'],$this->fillable);
        $list = $this->where($where)->orderBy('id','desc')->select($field)->paginate($limit);

        return $list;

    }

    /*
     * 保存数据
     * */
    public function changes( $data , $rule)
    {
        $validator = Validator::make( $data ,$rule ,$this->message);
        if($validator->fails()){
            $this->error = $validator->errors()->toMsg();
            return false;
        }

        DB::beginTransaction();
        try {

            if (isset($data['id']) && $data['id']){
                $upData = $this->stayFillData($this->fillable,$data);
                $result = WorkflowFlow::where('id',$data['id'])->update($upData);
            }else{
                $data['guid'] = getGuid();
                $result = WorkflowFlow::create($data);

            }
            if (!$result){
                throw new \Exception('新增产品失败 10001');
            }

            DB::commit();
            return $result;
        }catch (\Exception $exception){
            DB::rollBack();
            $this->error = $exception->getMessage();
            return false;
        }
    }




}
